<?php

namespace Home\Controller;

class WishController extends BaseMemberController {

    function _initialize() {
//        parent::_initialize();
        $this->_Member_mod = M("Member");
        $this->_user_id = session('visitor.user_id');
//        $this->_user_id = 3;
    }

    function index() {
        $res = M('wish')->join('left join ecm_member on ecm_wish.user_id = ecm_member.user_id')
                        ->join('left join ecm_goods on ecm_wish.goods_id = ecm_goods.goods_id')
                        ->where(array('ecm_wish.user_id' => $_POST['user_id']))
                        ->select();
        $res_textarea = M('textarea')->find();

        render('10000','获取成功',array('wish' => $res,'textarea'=>$res_textarea['wish']));
    }

    function drop() {
        if(!$_POST['user_id'] || !$_POST['goods_id']){
            render('10000','参数错误');
        }
        $cond['user_id'] = $_POST['user_id'];
        $cond['goods_id'] = $_POST['goods_id'];
        $res = M('wish')->where($cond)->delete();
        if(!$res){
            render('10003','删除失败');
        }
        render('10000','删除成功',array('wish' => $res));
    }

    function add_wish()
    {
        if(!I('request.spec_id')){
            render('10400', '请选择商品');
        }
        if(!I('request.number')){
            render('10400', '请选择数量');
        }
        if(!I('request.addr_id')){
            render('10400', '请选择地址id');
        }
        $payment_code =  I('request.payment_code');
        $payment_name = I('request.payment_name');
        if (!$payment_name || !$payment_code) {
            render('10525', '支付为空');
        }
        $res = M('goods_spec')->where(array('spec_id'=>I('request.spec_id')))->find();
        if ($res['stock'] < 1) {
            render('10003', '暂无库存');
        }
        //变价
        $goods_lists = M('goods')->field(C('DB_PREFIX') . 'store.state,' . C('DB_PREFIX') . 'store.store_name,' . C('DB_PREFIX') . 'goods.*,'. C('DB_PREFIX') . 'goods_spec.*,'. C('DB_PREFIX') . 'coupon_codes.store_id as sto_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'store  ON ' . C('DB_PREFIX') . 'goods.store_id = ' . C('DB_PREFIX') . 'store.store_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods_spec  ON ' . C('DB_PREFIX') . 'goods.goods_id = ' . C('DB_PREFIX') . 'goods_spec.goods_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'discount  ON ' . C('DB_PREFIX') . 'goods_spec.spec_id = ' . C('DB_PREFIX') . 'discount.spec_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'coupon_codes  ON ' . C('DB_PREFIX') . 'discount.coupon_codes_id = ' . C('DB_PREFIX') . 'coupon_codes.id')
            ->where( C('DB_PREFIX').'goods_spec.spec_id=' . I('request.spec_id'))
            ->find();
        //
        //判断价格

        if (I('token')) {
            $res_token = M('app_token')->where(array('token' => I('token')))->find();
            $res_user = M('member')->where(array('user_id' => $res_token['user_id']))->find();
        }else{
            $res_user = M('member')->where(array('user_id' => $this->_user_id))->find();
        }
        if ($goods_lists['sto_id'] && $res_user && strlen($goods_lists['sto_id']) && $goods_lists['sto_id'] != '0') {
            $res_store_goods = M('store')->where(array('store_id' => $goods_lists['sto_id']))->find();
            $res_store_user = M('store')->where(array('store_id' => $res_user['s_id']))->find();
            $res_region_goods = M('region')->where(array('region_id' => $res_store_goods['region_id']))->find();
            $res_region_user = M('region')->where(array('region_id' => $res_store_user['region_id']))->find();
            if($goods_lists['discount_price'] != '0.00' && $goods_lists['price'] != '0.00' && ($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id'])){
                $fn_price = $goods_lists['discount_price'] < $goods_lists['price'] ? $goods_lists['discount_price'] : $goods_lists['price'];
                $fn_tax_price = $goods_lists['discount_price'] < $goods_lists['price'] ? $goods_lists['tax_discount_price'] : $goods_lists['tax_price'];
                //标记 支付用
                $is_discount = true;
            }else{
                $fn_price = $goods_lists['price'];
                $fn_tax_price = $goods_lists['tax_price'];
                //标记 支付用
                $is_discount = false;
            }
        } else if (strlen($goods_lists['sto_id']) && $goods_lists['sto_id'] == '0') {
            //显示优惠价
            if($goods_lists['discount_price'] != '0.00' && $goods_lists['price'] != '0.00'){
                $fn_price = $goods_lists['discount_price'] < $goods_lists['price'] ? $goods_lists['discount_price'] : $goods_lists['price'];
                $fn_tax_price = $goods_lists['discount_price'] < $goods_lists['price'] ? $goods_lists['tax_discount_price'] : $goods_lists['tax_price'];
                //标记 支付用
                $is_discount = true;
            }else{
                $fn_price = $goods_lists['price'];
                $fn_tax_price = $goods_lists['tax_price'];
                //标记 支付用
                $is_discount = false;
            }
        } else {
            //显示普通价
            $fn_price = $goods_lists['price'];
        }
        $data['goods_id'] = $res['goods_id'];
        $data['user_id'] = $_POST['user_id'];
        $data['num'] = $_POST['number'];
        $data['spec_id'] = $_POST['spec_id'];
        $data['order_sn'] = date('YmdHis', time() + 8 * 3600) . rand(1000, 9999);
        $data['addr_id'] = $_POST['addr_id'];
        $data['price'] = C('WISH_PRICE');
        $data['discount'] = $goods_lists['discount'];
        //lichen linshigai
//        $data['goods_price'] = $is_discount ? $goods_lists['discount_price'] : $goods_lists['price'];
        $data['goods_price'] = $goods_lists['price'];
        //lichen linshigai
        //设备
        $data['device'] = $_POST['device'];
        $res = M('wish_temp')->add($data);
        if (!$res) {
            render('10003', '添加失败');
        }
        if ($payment_code == 'wxpay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $data['str'] = 'notifywx_wish.php';
            $payment->get_payform1($data);
        } elseif ($payment_code == 'alipay_app') {
            //调用支付宝支付
            import('Mall.Payment.Alipay.AliPayment', '', '.php');
            $payment = new \AliPayment();
            $data['str'] = 'notifyalipay_wish.php';
            $payment->get_payform1($data);
        } elseif ($payment_code == 'jspay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $data['str'] = 'notifywx_wish.php';
            $payment->get_payform3($data);
        }  else {
            render('19999', '未选择支付');
        }
    }

    function delete_all() {
        if(!$_POST['goods_id']){
            render('10004','参数错误');
        }

        $cond['goods_id'] = $_POST['goods_id'];
        $cond['user_id'] = $_POST['user_id'];
        $condc['item_id'] = $_POST['goods_id'];
        $condc['user_id'] = $_POST['user_id'];
        $res = M('wish')->where($cond)->delete();
        $resc = M('collect')->where($condc)->delete();
        render('10000','取消成功',$res);
    }

    function get_list(){
        if(!$_POST['user_id']){
            render('10004','参数错误');
        }
        if(!$_POST['page'] || !$_POST['pagenum']){
            render('10004', '参数错误');
        }
        $cond['ecm_wish.user_id'] = $_POST['user_id'];
        $res = M('wish')->field('ecm_wish.*,ecm_goods.goods_name,ecm_goods.default_image,ecm_goods_spec.price,ecm_goods_spec.stock,ecm_goods_spec.spec_1,ifnull(sum(ecm_wish_pay_log.money),0) as pay_money,CONCAT_WS(" ",ecm_goods_spec.spec_1value,ecm_goods_spec.spec_2) as _spec')
            ->join('left join ecm_goods on ecm_wish.goods_id = ecm_goods.goods_id')
            ->join('left join ecm_goods_spec on ecm_wish.spec_id =  ecm_goods_spec.spec_id')
            ->join('left join ecm_wish_pay_log on ecm_wish.id =  ecm_wish_pay_log.wish_id')
            ->group('ecm_wish.id')
            ->order('field(ecm_wish.state,1,0,2,3,4) asc,ecm_wish.add_time desc')
            ->limit($_POST['pagenum'])
            ->page($_POST['page'])
            ->where($cond)
            ->select();
        foreach ($res as $k => $v){
            $res_pay1 = M('wish_pay_log')->where(array('wish_id'=>$v['id'],'type'=>1))->find();
            $res[$k]['add_time'] = date("m月d日 H:i",$res[$k]['add_time']);
            $res[$k]['finish_time'] ? $res[$k]['finish_time'] = date("m月d日 H:i",$res[$k]['finish_time']) : 0;
            $res_log_money = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where(array('wish_id'=>$v['id']))->find();
            $res[$k]['pay_money'] = (float)$v['goods_price'] - (float)$res_pay1['money'] - (float)$res_log_money['smoney'];
            $res[$k]['over_price'] = (float)$v['goods_price'] - (float)$res_pay1['money'] - (float)$res_log_money['smoney'];
            //lichen lishigai
            $res[$k]['price'] = $v['goods_price'];
            $res[$k]['wish_price'] = $res_pay1['money'];
            //lichen lishigai
        }
        render('10000','查询成功',array('wish'=>$res));
    }

    function info(){
        if($_POST['wish_id']){
            $cond['id'] = $_POST['wish_id'];
        }else{
            if(!$_POST['user_id']){
                render('10004','参数错误');
            }
            $cond['state'] = 1;
            $cond['ecm_wish.user_id'] = $_POST['user_id'];
        }
        $res = M('wish')->field('ecm_wish.*,ecm_goods.goods_name,ecm_goods.default_image,0+cast(ecm_wish.discount*10 as char) as discounts,ecm_goods_spec.*,CONCAT_WS(" ",ecm_goods_spec.spec_1value,ecm_goods_spec.spec_2) as _spec')
            ->join('left join ecm_goods on ecm_wish.goods_id = ecm_goods.goods_id')
            ->join('left join ecm_goods_spec on ecm_wish.spec_id =  ecm_goods_spec.spec_id')
            ->order('add_time desc')
            ->where($cond)
            ->find();
        //lichen linshigai
        if($res){
            $res_pay1 = M('wish_pay_log')->where(array('wish_id'=>$res['id'],'type'=>1))->find();
            $conds['wish_id'] = $res['id'];
            $res['price'] = $res['goods_price'];
            $res['wish_price'] = $res_pay1['money'];
            $res['over_time'] = (string)($res['add_time'] + 60 * 86400 - time());
            $res['last_time'] = (string)($res['add_time'] + 60 * 86400);
            $res['share_str'] = '请帮我砍价吧 '.$res['goods_name'].'￥'.set_encrypt($res['id']).'￥';
            $res['share_title'] = '助力好友,达成心愿';
            $res['share_url'] = C('SITE_URL').'/mobile/index.php?app=share&act=shareWish&invite_code='.set_encrypt($res['user_id'].'|'.$res['id']);
            //小程序
            $res['invite_code'] = set_encrypt($res['user_id'].'|'.$res['id']);
            //
            $res['share'] =  C('SITE_URL').'/appserver/index.php?m=Home&c=Textarea&a=rull';

            $res_log = M('wish_log')->field('ecm_wish_log.*,ecm_member.user_name,ecm_member.portrait')->join('left join ecm_member on ecm_wish_log.inviter_id = ecm_member.user_id')->where($conds)->select();
            if($res_log){
                foreach ($res_log as $k => $v){
                     $v['user_name'] ? $res_log[$k]['user_name'] = substr_replace($v['user_name'], '****', 3, 4) : '';
                }
            }
            $res_log_money = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where($conds)->find();
            $res['over_price'] = (string)($res['price'] - $res_pay1['money'] - $res_log_money['smoney']);
            $res['log_price'] = $res_log_money['smoney'];
            $res['over_log_price'] = (string)($res['price'] - $res_pay1['money'] - $res_log_money['smoney']);
            $conds_pay['ecm_wish_pay_log.wish_id'] = $res['id'];
            $res_pay = M('wish_pay_log')->field('ecm_wish_pay_log.*,ecm_member.user_name,ecm_member.portrait')->join('left join ecm_member on ecm_wish_pay_log.user_id = ecm_member.user_id')->where($conds_pay)->select();
            if($res_pay){
                foreach ($res_pay as $k => $v){
                    $v['user_name'] && strlen($v['user_name']) == 11 ? $res_pay[$k]['user_name'] = substr_replace($v['user_name'], '****', 3, 4) : '';
                }
            }

        }

        $data['wish'] = $res ? $res : (object)array();
        $data['log'] = $res_log ? $res_log : array();
        $data['pay'] = $res_pay ? $res_pay : array();
        render('10000','查询成功',$data);
    }

    function finish_wish(){

        if(!I('request.wish_id')){
            render('10400', '请选择心愿单');
        }
        $payment_code =  I('request.payment_code');
        $payment_name = I('request.payment_name');
        if (!$payment_name || !$payment_code) {
            render('10525', '支付为空');
        }
        $cond_pay = array(
            'type' => 1,
            'wish_id' => I('request.wish_id')
        );
        $res_pay = M('wish_pay_log')->where($cond_pay)->find();
        if(!$res_pay){
            render('10003', '查找失败心愿单支付失败');
        }
        $cond['ecm_wish_pay_log.wish_id'] = I('request.wish_id');
        $cond['type'] = 1;
        $res = M('wish_pay_log')->join('left join ecm_wish_temp on ecm_wish_pay_log.wish_id = ecm_wish_temp.wish_id')->field('ecm_wish_pay_log.wish_id')->where($cond)->find();
        if(!$res){
            render('10003', '添加失败');
        }
        $conds['id'] = I('request.wish_id');
        $res_wish = M('wish')->field('ecm_wish.*,ecm_goods.goods_name,ecm_goods.default_image,ecm_goods_spec.*,CONCAT_WS(" ",ecm_goods_spec.spec_1value,ecm_goods_spec.spec_2) as _spec')
            ->join('left join ecm_goods on ecm_wish.goods_id = ecm_goods.goods_id')
            ->join('left join ecm_goods_spec on ecm_wish.spec_id =  ecm_goods_spec.spec_id')
            ->order('add_time desc')
            ->where($conds)
            ->find();
        if(!$res_wish['stock']){

            render('10003', '无库存了请联系客服');
        }
        $res_log = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where(array('wish_id'=>$_POST['wish_id']))->find();
        $data = array(
            'price' => (float)$res_wish['goods_price'] - (float)$res_log['smoney'] - (float)$res_pay['money'],
            'order_sn' => date('YmdHis', time() + 8 * 3600) . rand(1000, 9999),
        );
        $res_temp = M('wish_temp')->where(array('wish_id'=>I('request.wish_id')))->save(array('order_sn2'=>$data['order_sn']));
        if($res_temp === false){
            render('10003', '修改失败');
        }
        if ($payment_code == 'wxpay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $data['str'] = 'notifywx_finish_wish.php';
            $payment->get_payform1($data);
        } else if ($payment_code == 'alipay_app') {
            //调用支付宝支付
            import('Mall.Payment.Alipay.AliPayment', '', '.php');
            $payment = new \AliPayment();
            $data['str'] = 'notifyalipay_finish_wish.php';
            $payment->get_payform1($data);
        } else {
            render('19999', '未选择支付');
        }
    }


    function cancel_wish(){
        if(!I('request.wish_id')){
            render('10400', '请选择心愿单');
        }
        $cond['wish_id'] = I('request.wish_id');
        $cond['state'] = 1;
        $res_pay = M('wish_pay_log')->where($cond)->find();
        $res_wish = M('wish')->where(array('id'=>I(('request.wish_id'))))->find();
        if(!$res_pay){
            render('10004', '未找到心愿单');
        }
        $time = date('YmdHis', time() + 8 * 3600) . rand(1000, 9999);
        if($res_pay['pay_type'] == 1){
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($res_pay['order_sn']);
            $input->SetTotal_fee($res_pay['money'] * 100);
            $input->SetRefund_fee($res_pay['money'] * 100);
            $config = new \WxPay1Config();
            $input->SetOut_refund_no($time);
//            $input->SetOp_user_id($config->GetMerchantId());
            $rs = \WxPay1Api::refund($config,$input, 60);
            if($rs['return_code'] != 'SUCCESS'){
                render('10004', '退款失败');
            }
            $data_oms = array(
                'ClientGuid' => '4CC68510-AAD3-4DBC-9131-F00E5FFD2E75',
                'ClientName' => 'ASA-ShoppingMall',
                'BillNo' => date("YmdHis",$res_wish['add_time']).$res_pay['wish_id'],
                'BillType' => 20,
                'PayName' => '财付通支付科技有限公司',
                'PayCode' => '4403169D3W',
                'PayTransactionId' => $rs['transaction_id'],
                'PayPrice' => (float)($rs['refund_fee'] / 100),
                'RefundNo' => $time
            );
        }else if($res_pay['pay_type'] == 2){
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/Alipay/aop/AopCertClient.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/Alipay/aop/request/AlipayTradeRefundRequest.php";
            $appCertPath = "/data/wwwroot/default/ecmall/includes/alicert/appCertPublicKey_2019052465373222.crt";
            $alipayCertPath = "/data/wwwroot/default/ecmall/includes/alicert/alipayCertPublicKey_RSA2.crt";
            $rootCertPath = "/data/wwwroot/default/ecmall/includes/alicert/alipayRootCert.crt";
            $aop = new \AopCertClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = C('app_alipay_partner_id');
            $aop->rsaPrivateKey =C('app_alipay_private_key');
            $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
            $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
            $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
            $request = new \AlipayTradeRefundRequest ();

            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($res_pay['order_sn']);
            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($res_pay['money']);

            $request->setBizContent("{" .
                "\"out_trade_no\":\"$out_trade_no\"," .
                "\"trade_no\":\"\"," .
                "\"refund_amount\":\"$refund_amount\"," .
                "\"refund_reason\":\"正常退款\"" .
                "  }");
            $result = $aop->execute($request);
//            $rs= json_decode(json_encode($result),true);
            $response = $result->alipay_trade_refund_response;
//            $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
////                $out_request_no = trim($_POST['WIDTRout_request_no']);
//
//            //构造参数
//            $RequestBuilder=new \AlipayTradeRefundContentBuilder();
//            $RequestBuilder->setOutTradeNo($out_trade_no);
////                $RequestBuilder->setTradeNo($trade_no);
//            $RequestBuilder->setRefundAmount($refund_amount);
////                $RequestBuilder->setOutRequestNo($out_request_no);
////                $RequestBuilder->setRefundReason($refund_reason);
//            $aop = new \AlipayTradeService($config,true);
//            $response = $aop->Refund($RequestBuilder);

            if($response->code != '10000'){
                render('10004', '退款失败');
            }
            $data_oms = array(
                'ClientGuid' => '4CC68510-AAD3-4DBC-9131-F00E5FFD2E75',
                'ClientName' => 'ASA-ShoppingMall',
                'BillNo' => date("YmdHis",$res_wish['add_time']).$res_pay['wish_id'],
                'BillType' => 20,
                'PayName' => '财付通支付科技有限公司',
                'PayCode' => '4403169D3W',
                'PayTransactionId' => $response->trade_no,
                'PayPrice' => $response->refund_fee,
                'RefundNo' => $time.rand('1000,9999')
            );
        }else{
            render('10004', '未找到心愿单');
        }

        $res = sync_data(C('CANCEL_WISH_URL'),$data_oms);

        $data_wish = array(
            'state' => 0,
            'finish_time' => time()
        );
        $res_pay = M('wish')->where(array('id'=>I('request.wish_id')))->save($data_wish);
        if($res_pay === false){
            render('10004', '修改状态失败');
        }

        $data_wish = array(
            'state' => 0,
            'finish_time' => time()
        );
        $res_pay = M('wish')->where(array('id'=>I('request.wish_id')))->save($data_wish);
        if($res_pay === false){
            render('10004', '修改状态失败');
        }

        $res_wish = M('wish')->where(array('id'=>I('request.wish_id')))->find();

        $res_spec = M('goods_spec')->where(array('spec_id'=>$res_wish['spec_id']))->setInc('stock');

        if(!$res_spec){
            render('10004', '库存回滚失败');
        }

        render('10000', '退款成功');


    }

//    function cancel_order_test(){
//        $cond['order_sn'] = $_POST['order_sn'];
//        $res_pay = M('order')->where($cond)->find();
//        //order_amount
//        if($res_pay['payment_code'] == 'wxpay_app'){
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
//            $input = new \WxPayRefund();
//            $input->SetOut_trade_no($res_pay['order_sn']);
//            $input->SetTotal_fee($res_pay['order_amount'] * 100);
//            $input->SetRefund_fee($res_pay['order_amount'] * 100);
//            $config = new \WxPay1Config();
//            $input->SetOut_refund_no(date('YmdHis', time() + 8 * 3600) . rand(1000, 9999));
////            $input->SetOp_user_id($config->GetMerchantId());
//            $rs = \WxPay1Api::refund($config,$input, 60);
////                $this->printf_info(WxPay1Api::refund($config,$input, 60));
//            if($rs['return_code'] != 'SUCCESS'){
//                render('10004', '退款失败');
//            }
//        }else if($res_pay['payment_code'] == 'alipay_app'){
//            $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
//            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
//            //商户订单号，商户网站订单系统中唯一订单号
//            $out_trade_no = trim($res_pay['order_sn']);
//
//            //支付宝交易号
////                $trade_no = trim($_POST['WIDTRtrade_no']);
//            //请二选一设置
//
//            //需要退款的金额，该金额不能大于订单金额，必填
//            $refund_amount = trim($res_pay['order_amount']);
//
//            //退款的原因说明
////                $refund_reason = trim($_POST['WIDTRrefund_reason']);
//
//            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
////                $out_request_no = trim($_POST['WIDTRout_request_no']);
//
//            //构造参数
//            $RequestBuilder=new \AlipayTradeRefundContentBuilder();
//            $RequestBuilder->setOutTradeNo($out_trade_no);
////                $RequestBuilder->setTradeNo($trade_no);
//            $RequestBuilder->setRefundAmount($refund_amount);
////                $RequestBuilder->setOutRequestNo($out_request_no);
////                $RequestBuilder->setRefundReason($refund_reason);
//            $aop = new \AlipayTradeService($config,true);
//            $response = $aop->Refund($RequestBuilder);
//
//            if($response->code != '10000'){
//                render('10004', '退款失败');
//            }
//        }else{
//            render('10004', '未找到心愿单');
//        }
//
//        render('10000', '退款成功');
//    }
//

    function cancel_wish_refund($wish_id){
        if($wish_id){
            render('10400', '请选择心愿单');
        }
        $cond['wish_id'] = $wish_id;
        $cond['state'] = 1;
        $res_pay = M('wish_pay_log')->where($cond)->find();
        if(!$res_pay){
            render('10004', '未找到心愿单');
        }
        if($res_pay['pay_type'] == 1){
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($res_pay['order_sn']);
            $input->SetTotal_fee($res_pay['money'] * 100);
            $input->SetRefund_fee($res_pay['money'] * 100);
            $config = new \WxPay1Config();
            $input->SetOut_refund_no(date('YmdHis', time() + 8 * 3600) . rand(1000, 9999));
//            $input->SetOp_user_id($config->GetMerchantId());
            $rs = \WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
            if($rs['return_code'] != 'SUCCESS'){
                render('10004', '退款失败');
            }
        }else if($res_pay['pay_type'] == 2){
            $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($res_pay['order_sn']);

            //支付宝交易号
//                $trade_no = trim($_POST['WIDTRtrade_no']);
            //请二选一设置

            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($res_pay['money']);

            //退款的原因说明
//                $refund_reason = trim($_POST['WIDTRrefund_reason']);

            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);

            //构造参数
            $RequestBuilder=new \AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
//                $RequestBuilder->setTradeNo($trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
//                $RequestBuilder->setOutRequestNo($out_request_no);
//                $RequestBuilder->setRefundReason($refund_reason);
            $aop = new \AlipayTradeService($config,true);
            $response = $aop->Refund($RequestBuilder);

            if($response->code != '10000'){
                render('10004', '退款失败');
            }
        }else{
            render('10004', '未找到心愿单');
        }

        $data_wish = array(
            'state' => 0,
            'finish_time' => time()
        );
        $res_pay = M('wish')->where(array('id'=>$wish_id))->save($data_wish);
        if($res_pay === false){
            render('10004', '修改状态失败');
        }
        render('10000', '退款成功');


    }
    function cancel_wish_test(){
        if(!I('request.order_sn')){
            render('10400', '请选择心愿单');
        }
        $cond['order_sn'] = I('request.order_sn');
        $res_pay = M('wish_pay_log')->where($cond)->find();
        if(!$res_pay){
            render('10004', '未找到心愿单');
        }
        if($res_pay['pay_type'] == 1){
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($res_pay['order_sn']);
            $input->SetTotal_fee($res_pay['money'] * 100);
            $input->SetRefund_fee($res_pay['money'] * 100);
            $config = new \WxPay1Config();
            $input->SetOut_refund_no(date('YmdHis', time() + 8 * 3600) . rand(1000, 9999));
//            $input->SetOp_user_id($config->GetMerchantId());
            $rs = \WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
            if($rs['return_code'] != 'SUCCESS'){
                render('10004', '退款失败');
            }
        }else if($res_pay['pay_type'] == 2){
            $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($res_pay['order_sn']);

            //支付宝交易号
//                $trade_no = trim($_POST['WIDTRtrade_no']);
            //请二选一设置

            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($res_pay['money']);

            //退款的原因说明
//                $refund_reason = trim($_POST['WIDTRrefund_reason']);

            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);

            //构造参数
            $RequestBuilder=new \AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
//                $RequestBuilder->setTradeNo($trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
//                $RequestBuilder->setOutRequestNo($out_request_no);
//                $RequestBuilder->setRefundReason($refund_reason);
            $aop = new \AlipayTradeService($config,true);
            $response = $aop->Refund($RequestBuilder);

            if($response->code != '10000'){
                render('10004', '退款失败');
            }
        }else{
            render('10004', '未找到心愿单');
        }

        render('10000', '退款成功');


    }

    function get_other_wish(){
        $res = M('wish')->field('ecm_goods.goods_name,ecm_member.portrait,ecm_member.user_name,ecm_wish.*,sum(ecm_wish_pay_log.money) as all_price')
                        ->join('left join ecm_member on ecm_wish.user_id = ecm_member.user_id')
                        ->join('left join ecm_goods on ecm_wish.goods_id = ecm_goods.goods_id')
                        ->join('left join ecm_wish_pay_log on ecm_wish.id = ecm_wish_pay_log.wish_id')
                        ->where(array('state'=>2))
                        ->group('ecm_wish.id')
                        ->order('finish_time desc')
                        ->limit(5)
                        ->select();
        $data = array();
        foreach ($res as $k => $v){
            $data[] = array(
                'portrait' => $v['portrait'],
                'content' => strlen($v['user_name']) == 11 ? substr_replace($v['user_name'], '****', 3, 4).'刚以￥'.$v['all_price'].'获得'.$v['goods_name'] : $v['user_name'].'刚以￥'.$v['all_price'].'获得'.$v['goods_name'],
            );
        }
        $result['data'] = $data;

        render('10000', '获取列表成功',(object)$result);

    }

    function wish_log($user_id = 3,$referid = 7077,$wish_id = 231){
        $rs = get_wish_log_price($wish_id,2);
        if($rs){
            //算总钱数
//            $rs_log = M('wish_log')->field('ifnull(sum(money),0) as smoney')->where(array('wish_id'=>$wish_id))->find();
            $data = array(
                'wish_id' => $wish_id,
                'user_id'=> $user_id,
                'inviter_id' => $referid,
                'money' => $rs['money'],
                'msg' => '帮砍金额',
                'create_time' => time(),
                'sign' => $rs['sign'],
                'stage' => $rs['stage']
            );
            M('wish_log')->add($data);
            $res_coupon_setting = M('coupon_setting')->where(array('setting_id'=>1))->find();
            $data_coupon = array(
                'coupon_name' => '境内仓通用优惠券',
                'remark' => $res_coupon_setting['remark'],
                'money' => $res_coupon_setting['money'],
                'min_money' => $res_coupon_setting['min_money'],
                'user_id' => $referid,
                'start_time' => time(),
                'end_time' => time()+$res_coupon_setting['expiry_time'],
                'is_used' => 0,
            );
            M('member_coupon')->add($data_coupon);
            if($rs['fsh']){
                //完成订单
                $rs = D('wish')->createOrder($wish_id);

            }
        }

    }

    function wish_log_test($user_id = 3,$referid = 222,$wish_id = 25){

         $rs = D('wish')->createOrder($_POST['wish_id']);


    }

    function get_member_coupon(){
        $cond_coupon['user_id'] = $_POST['user_id'];
        if(!$_POST['page'] || !$_POST['pagenum']){
            render('10004', '参数错误');
        }
        if($_POST['is_used'] || isset($_POST['is_used'])){
            $cond_coupon['is_used'] = $_POST['is_used'];
            $cond_coupon['end_time'] = array('egt',time());
        }else if($_POST['is_overdue']){
            $cond_coupon['end_time'] = array('elt',time());
        }
        $res_member_coupon = M('member_coupon')->where($cond_coupon)->limit($_POST['pagenum'])->page($_POST['page'])->select();
        foreach ($res_member_coupon as $k => $v){
            $res_member_coupon[$k]['remark'] = 'APP专享|'.$v['remark'];
            $res_member_coupon[$k]['start_time'] = date("Y-m-d H:i",$v['start_time']);
            $res_member_coupon[$k]['end_time'] = date("Y-m-d H:i",$v['end_time']);
        }
        //数量
        $res1 = M('member_coupon')->where(array('user_id'=>$_POST['user_id'],'is_used'=>0,'end_time'=>array('egt',time())))->count();
        $res2 = M('member_coupon')->where(array('user_id'=>$_POST['user_id'],'is_used'=>1,'end_time'=>array('egt',time())))->count();
        $res3 = M('member_coupon')->where(array('user_id'=>$_POST['user_id'],'end_time'=>array('elt',time())))->count();
        $res_count['not_used'] = $res1;
        $res_count['is_used'] = $res2;
        $res_count['is_overdue'] = $res3;
        $res_back = M('limited_setting')->find();
        render('10000', '获取列表成功',array('data'=>$res_member_coupon,'count'=>$res_count,'background'=>''));
//        render('10000', '获取列表成功',array('data'=>$res_member_coupon,'count'=>$res_count,'background'=>C('site_url').'/'.$res_back['coupon_image']));
    }

    function addWish(){
        if(!$_POST['spec_id'] || !$_POST['user_id'] || !$_POST['addr_id']){
            render('10004', '参数错误');
        }
        $spec = M('goods_spec')->where(array('spec_id'=>$_POST['spec_id']))->find();
        $goods = M('goods')->where(array('goods_id'=>$spec['goods_id']))->find();
        if(!$spec || !$goods){
            render('10004', '添加失败');
        }

        $wish = array(
            'user_id' => $_POST['user_id'],
            'spec_id' => $_POST['spec_id'],
            'num' => 1,
            'addr_id' => $_POST['addr_id'],
            'goods_id' => $spec['goods_id'],
            'add_time' =>time(),
            'state' => 1,
            'goods_price' => $spec['price'],
            'discount' => $goods['discount']
        );
        $res_wish = M('wish')->add($wish);
        $wish_temp = array(
            'user_id' => $_POST['user_id'],
            'spec_id' => $_POST['spec_id'],
            'num' => 1,
            'addr_id' => $_POST['addr_id'],
            'goods_id' => $spec['goods_id'],
            'goods_price' => $spec['price'],
            'wish_id' => $res_wish
        );
        $res_wish_temp = M('wish_temp')->add($wish_temp);
        $wish_pay_log = array(
            'wish_id' => $res_wish,
            'user_id' => $_POST['user_id'],
            'type' => 1,
            'spec_id' => $_POST['spec_id'],
            'num' => 1,
            'addr_id' => $_POST['addr_id'],
            'goods_id' => $spec['goods_id'],
            'remark' => '我创建了一个心愿单',
            'create_time' => time()
        );
        $res_wish_pay_log = M('wish_pay_log')->add($wish_pay_log);
        render('10000', '添加成功');
    }


}